// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

db = cloud.database();

const MAX_LIMIT = 100; //服务端limit的上限

//获取当前时间，格式YYYY-MM-DD
function getNowFormatDate() {
  var date = new Date();
  var seperator1 = "-";
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}

// 云函数入口函数
exports.main = async (event, context) => {

  let userId = event.userId; //用户编号
  let todayDate = getNowFormatDate();

  //获取预设值的订单状态
  let statusSet = await db.collection('settings').get()
  let status = statusSet.data[0].orderStatus //获取状态数组
  let orders = []; //所有订单记录
  //遍历所有状态
  for (let n = 0; n < status.length; n++) {
    let oneStatus = status[n]
    let condition = {
      userId: userId,
      status: oneStatus,
      orderDate: todayDate
      //orderDate: '2018-09-18'
    } //查询条件
    // 先取出集合记录总数
    let countResult = await db.collection('orders').where(condition).count()
    let total = countResult.total
    // 计算需分几次取
    let batchTimes = Math.ceil(total / 100)
    // 承载所有读操作的 promise 的数组
    let tasks = []
    for (let i = 0; i < batchTimes; i++) {
      let promise = db.collection('orders').skip(i * MAX_LIMIT).limit(MAX_LIMIT)
        .where(condition) //条件：用户id，当前状态，当日日期
        .field({
          orderId: true,
          simpleId: true,
          orderTypeName: true,
          orderDate: true,
          orderTime: true,
          totalCount: true,
          totalCost: true,
          status: true,
        })
        .orderBy('oneDayId', 'desc') //按照下单流水号降序排列
        .get()
      tasks.push(promise)
    }
    if (batchTimes == 0) {
      //如果没有满足条件的记录
      orders.push([]);
    } else {
      // 等待所有
      let allPromise = await (async function (promises) {
        return (await Promise.all(tasks)).reduce((acc, cur) => {
          return {
            data: acc.data.concat(cur.data),
            errMsg: acc.errMsg,
          }
        })
      })(tasks)
      //将此状态下的所有订单，放入orders中
      orders.push(allPromise.data)
    }
  }
  return {
    status: status,
    orders: orders
  }
}